//
//  LFOauthViewController.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/21.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit
import SVProgressHUD
class LFOauthViewController: UIViewController{
    
    override func loadView() {
        
        view = webView;
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        let urlString :String = "https://api.weibo.com/oauth2/authorize?client_id=\(LFClient_id)&redirect_uri=\(LFRedirect_uri)"
        
//        print("urlString:\(urlString)")
        let url =  NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView .loadRequest(request)
        
        //showWithStatus需要手动关闭
         SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.None)
        
        //增添导航栏按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "stuffAction")
    }
    
    
    //MARK : -- 导航栏按钮点击事件
    //点击填充
    func stuffAction() {
        //自动填充
        let jsId = "document.getElementById('userId').value='liujianhehe@sina.cn';document.getElementById('passwd').value='2693355'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsId)
    }
    
    //点击取消
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
     //MARK : -- webView开始加载
    
    
    //MARK : -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}

   //MARK : --  扩展
extension LFOauthViewController: UIWebViewDelegate {
    //加载完成之后调用
    func webViewDidFinishLoad(webView: UIWebView) {
       //    关闭提示
        SVProgressHUD.dismiss()
    }
    
    //点击加载之前调用 : 返回 true 表示加载  返回false 表示不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
//        print("urlString:\(urlString)")
        
//        https://api.weibo.com/oauth2/authorize 在点击登录时候 回调的地址
        
//        http://www.clemmieliu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330" 点击取消回调地址
        
//   http://www.clemmieliu.com/?code=ce61c7dec7582a10b1bb2360b2941497 点击了授权回调的地址
        //1.如果回调地址不是以http://www.clemmieliu.com 开头 则让他继续加载
        if !(urlString.hasPrefix(LFRedirect_uri)) {
            
            return true
        }else {
            //判断点击授权与取消
            let queryString = request.URL!.query
         
            let preString = "code="
            
            if queryString!.hasPrefix(preString) {
                //点击了授权
                
                // queryString 转换类型
                let nspreString = queryString! as NSString
                //1.获取code
                let codeString = nspreString.substringFromIndex(preString.characters.count)
               
                //2.网络请求获取access_token
                LFGlobalUserAccountsViewModel.sharedUserAccounts.loadAccesstoken(codeString, completion: { (error) -> () in
                    if error != nil {
                        //提示
                         SVProgressHUD.showErrorWithStatus("获取Token失败")
                        
                        //一秒后提示关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            SVProgressHUD.dismiss()
                        })
                    }else {
                        //做跳转处理加载数据
                        AppDelegate.JumpViewController(LFWelComeViewController())
                        self.close()
                    }
                })
                
            }else {
                //点击了取消
                close()
            }
        }
        
        return false
    }
    
      
    
}
